# -*- coding: utf-8 -*-
# @Time: 2021/12/9 18:13
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: serializers.py
# @Software: PyCharm
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField
from rest_framework.serializers import ModelSerializer

from .models import *


# 分级表需要两个及以上序列化器
class ClassificationSerializer(ModelSerializer):  # 子序列化器
    class Meta:
        model = Classification
        fields = ['id', 'name', 'parent']
        extra_kwargs = {
            'parent': {'write_only': True}
        }


class ParentClassificationSerializer(ModelSerializer):  # 父序列化器
    classification_set = ClassificationSerializer(many=True, read_only=True)

    class Meta:
        model = Classification
        fields = ['id', 'name', 'parent', 'classification_set']
        extra_kwargs = {
            'parent': {'write_only': True}
        }


class CommodityImgSerializer(ModelSerializer):
    class Meta:
        model = CommodityImg
        fields = ['src']


class CommoditySerializer(ModelSerializer):
    classification1_name = serializers.CharField(source='classification1.name', read_only=True)
    classification2_name = serializers.CharField(source='classification2.name', read_only=True)
    commodityimg_set = CommodityImgSerializer(many=True, read_only=True)

    class Meta:
        model = Commodity
        exclude = ['is_delete']


class ShoppingCartSerializer(ModelSerializer):
    class Meta:
        model = ShoppingCart
        fields = '__all__'

    commodityDetail = SerializerMethodField()

    # data['commodity']得到的是一个对象
    def validate(self, data):
        if data['number'] <= 0 or data['number'] > data['commodity'].stock:
            raise serializers.ValidationError('number error')
        return data

    def get_commodityDetail(self, shoppingcart):
        # 每条购物车数据都走一遍这个函数
        return CommoditySerializer(shoppingcart.commodity).data


class OrderSerializer(ModelSerializer):
    cart = serializers.ListField(write_only=True)  # 这个字段存购物车中要结算的商品id

    class Meta:
        model = Order
        fields = '__all__'
        extra_kwargs = {
            'order_id': {'read_only': True},
            'user': {'read_only': True}
        }

    def create(self, validated_data):  # 走到这个create方法已经经过了校验
        # 订单编号

        # 事务控制
        # 创建保存点

        # try的部分:
        # 创建订单信息
        #
        # 获取购物车中被勾选的商品  得到勾选的购物车id，有多个商品所以是个列表，所以序列化器要添加字段
        #
        # 判断是否超出库存 超出则回滚
        #
        # 库存操作 减少库存 增加销量
        #
        # 将购物车中要结算的商品 保存到订单商品表中
        #
        # 得到总数量和总价
        #
        # 修改订单信息

        # except:
        # 回滚

        # 清除购物车已结算的商品
        pass
